<template>
  <div class="app-container">
    <list-page :showPage="false" @getList="getList">
      <template #search>
        <list-search v-model="searchForm" @search="search">
          <el-form-item label="地区名称" prop="like.name">
            <el-input v-model="searchForm.like.name" placeholder="请输入地区名称" clearable @keyup.enter="search" />
          </el-form-item>
          <el-form-item label="状态" prop="where.status">
            <el-select v-model="searchForm.where.status" clearable class="w-120px">
              <el-option v-for="dict in sys_show_hide" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </list-search>
      </template>

      <template #actions>
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPerm="['base:city:add']"
          >新增省份</el-button
        >
        <el-button type="info" plain icon="Sort" @click="handleExpand">展开/折叠</el-button>
      </template>

      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="listData"
        row-key="id"
        lazy
        :load="loadChildren"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="name" label="地区名称" min-width="150" />
        <el-table-column prop="area_code" label="区号" align="center" min-width="80" />
        <el-table-column prop="short_name" label="简称" align="center" min-width="80" />
        <el-table-column prop="merge_name" label="组合名称" align="center" min-width="100" />
        <el-table-column label="中心坐标" align="center" min-width="100">
          <template #default="scope">
            <el-link :underline="false" type="primary" @click="handlerCoordMap(scope.row)">
              {{ scope.row.lng }},{{ scope.row.lat }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" min-width="60">
          <template #default="scope">
            <dict-tag :options="sys_show_hide" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" class-name="small-padding">
          <template v-slot="{ row }">
            <el-button link type="primary" icon="Edit" @click="handleEdit(row)" v-hasPerm="['base:city:edit']"
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              icon="Plus"
              @click="handleAdd(row)"
              v-hasPerm="['base:city:add']"
              v-if="row.level < 2"
              >新增</el-button
            >
            <el-button link type="primary" icon="Delete" @click="handleDelete(row)" v-hasPerm="['base:city:delete']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </list-page>

    <post-form :module-name="moduleName" v-model="formShow" :row="formData" @submit="formSubmit" v-if="formShow" />

    <coord-select
      v-model="showCoordMap"
      :longitude="showCoordRow.lng"
      :latitude="showCoordRow.lat"
      disabled
      v-if="showCoordMap" />
  </div>
</template>

<script setup name="City">
  import { listCityApi, delCityApi } from '@/api/system/city'
  import CoordSelect from '@/components/widgets/CoordSelect/index.vue'
  import PostForm from './form.vue'

  const { proxy } = getCurrentInstance()
  const moduleName = ref('地区')
  const searchForm = ref({
    isTotal: 1,
    where: { status: undefined, parent_id: 0 },
    like: { name: undefined }
  })
  const { sys_show_hide } = proxy.useDict('sys_show_hide')

  onMounted(() => getList())

  // 查询列表
  const loadNode = new Map()
  const loading = ref(true)
  const listData = ref([])
  function getList() {
    loading.value = true
    listCityApi(searchForm.value).then(res => {
      let list = res?.list || []
      list = list.map(item => {
        item.hasChildren = true
        return item
      })
      listData.value = list
      loading.value = false
    })
  }

  // 加载子节点，
  function loadChildren(tree, treeNode, resolve) {
    let searchParams = proxy.deepClone(searchForm.value)
    searchParams.where.parent_id = tree.id
    listCityApi(searchParams).then(res => {
      let list = res?.list || []
      if (tree.level < 1) {
        list = list.map(item => {
          item.hasChildren = true
          return item
        })
      }
      loadNode.set(tree.id, { tree, treeNode, resolve })
      resolve(list)
    })
  }

  // 修改添加删除后刷新列表，需要重新加载父级节点
  function formSubmit() {
    if (formData.value.parent_id && loadNode.get(formData.value.parent_id)) {
      const { tree, treeNode, resolve } = loadNode.get(formData.value.parent_id)
      if (tree) loadChildren(tree, treeNode, resolve)
    } else {
      getList()
    }
  }

  // 搜索和重置
  function search() {
    getList()
  }

  // 新增和编辑
  const formData = ref(null)
  const formShow = ref(false)
  function handleAdd(row) {
    formData.value = { parent_id: row?.id || 0, parent_name: row?.name || '' }
    formShow.value = true
  }
  function handleEdit(row) {
    const editId = row?.id || 0
    if (!editId) return proxy.$modal.msgError('参数缺失')
    formData.value = { id: editId, parent_id: row?.parent_id || 0 }
    formShow.value = true
  }

  // 展开/折叠操作
  const isExpandAll = ref(false)
  const refreshTable = ref(true)
  function handleExpand() {
    refreshTable.value = false
    isExpandAll.value = !isExpandAll.value
    nextTick(() => {
      refreshTable.value = true
    })
  }

  // 删除按钮操作
  function handleDelete(row) {
    let delIds = row?.id || null
    if (!delIds) return proxy.$modal.msgError('参数缺失')
    proxy.$modal
      .confirm('是否确认删除' + moduleName.value + '名称为"' + row.name + '"的数据项?')
      .then(() => {
        return delCityApi(delIds)
      })
      .then(() => {
        formData.value = { parent_id: row?.parent_id || 0 }
        formSubmit()
        proxy.$modal.msgSuccess(res?.msg || '删除成功')
      })
      .catch(() => {})
  }

  // 展示坐标位置
  const showCoordMap = ref(false)
  const showCoordRow = ref(null)
  function handlerCoordMap(row) {
    showCoordRow.value = row
    showCoordMap.value = true
  }
</script>
